package mavenProject.DAO;

import java.sql.SQLException;
import java.util.List;

import mavenProject.Model.UserResult;

import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class ResultUserDAO {

	private HibernateTemplate hibernateTemplate;

//	@Autowired
//	public void init(SessionFactory factory) {
//	    setSessionFactory(factory);
//	}
	
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
	hibernateTemplate = new HibernateTemplate(sessionFactory);
	 }
	
	
	public void saveResult(UserResult result) {
		hibernateTemplate.saveOrUpdate(result);
		
	}

	public UserResult getResult(int idUser) {
//		Criteria criteria = getSession().createCriteria(UserResult.class);		
//		criteria.add(Restrictions.eq("idUser", idUser));
//		if(criteria.uniqueResult().equals(null)){
//			return null;
//		}
//		
//		return  (UserResult) criteria.uniqueResult();
		
		// SQL query to the model
		List<UserResult> results = hibernateTemplate.find("from UserResult where idUser = " + idUser);
		if (results.isEmpty()) {
			return null;
		}
		
		//return (UserResult) hibernateTemplate.find(
		//		"from UserResult where idUser = " + IdUser).get(0);
		return results.get(0);
	}

	public int getIdRightAnswer(final int idQuestion) {
//		Criteria criteria = getSession().createCriteria(Question.class);		
//		criteria.add(Restrictions.eq("id", idQuestion));
//		criteria.add(Restrictions.isNotNull("rightAnswer"));
//		
//		return (Integer) criteria.uniqueResult();
		
		
		
		return hibernateTemplate.execute(new HibernateCallback<Integer>() {

			public Integer doInHibernate(Session session) throws HibernateException, SQLException {
				// SQL query to database
				SQLQuery query = session.createSQLQuery("Select CorrectAnswer from questions where questionID = "+idQuestion);
	
				return (Integer) query.uniqueResult();
			}
		}).intValue();

	}
}
